import 'dart:async';

import 'package:auto_size/auto_size.dart';
import 'package:flutter/material.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:fsharing/core/constants/app_contstants.dart';
import 'package:fsharing/core/services/api.dart';
import 'package:fsharing/core/services/auth.dart';
import 'package:fsharing/core/viewmodels/app_model.dart';
import 'package:fsharing/generated/i18n.dart';
import 'package:fsharing/ui/router.dart';
import 'package:fsharing/ui/widgets/no_scale_text_widget.dart';
import 'package:oktoast/oktoast.dart';
import 'package:provider/provider.dart';
import 'package:fluwx/fluwx.dart' as fluwx;
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:sentry/sentry.dart';

/// Sentry.io client used to send crash reports (or more generally "events").
final SentryClient _sentry = SentryClient(dsn: dsn);

/// Whether the VM is running in debug mode.
bool get isInDebugMode {
  bool inDebugMode = false;
  assert(inDebugMode = true);
  return inDebugMode;
}

/// Reports [error] along with its [stackTrace] to Sentry.io.
Future<Null> _reportError(dynamic error, dynamic stackTrace) async {
  print('Caught error: $error');

  if (isInDebugMode) {
    print(stackTrace);
    print('In dev mode. Not sending report to Sentry.io.');
    return;
  }

  print('Reporting to Sentry.io...');

  final SentryResponse response = await _sentry.captureException(
    exception: error,
    stackTrace: stackTrace,
  );

  if (response.isSuccessful) {
    print('Success ! Event ID: ${response.eventId}');
  } else {
    print('Failed to report to Sentry.io: ${response.error}');
  }
}

void main() async {
  // This captures errors reported by the Flutter framework.
  FlutterError.onError = (FlutterErrorDetails details) async {
    if (isInDebugMode) {
      FlutterError.dumpErrorToConsole(details);
    } else {
      Zone.current.handleUncaughtError(details.exception, details.stack);
    }
  };

  runZoned<Future<Null>>(() async {
    runAutoSizeApp(App(), width: 375, height: 667);
  }, onError: (error, stackTrace) async {
    await _reportError(error, stackTrace);
  });
}

class App extends StatefulWidget {
  // This widget is the root of your application.
  @override
  _AppState createState() => _AppState();
}

class _AppState extends State<App> {
  @override
  void initState() {
    super.initState();
    // 注册微信
    fluwx.registerWxApi(
      appId: wx_app_id,
      universalLink: wx_universal_link,
    );
  }

  @override
  Widget build(BuildContext context) {
    return MultiProvider(
      providers: [
        ChangeNotifierProvider(create: (context) => AppStoreModel()),
        ChangeNotifierProvider(create: (context) => AppLoginModel()),
        ProxyProvider2<AppStoreModel, AppLoginModel, Auth>(update: (_, t, t2, __) => Auth(t, t2)),
        ProxyProvider2<AppStoreModel, AppLoginModel, Api>(update: (_, t, t2, __) => Api(t, t2)),
      ],
      child: OKToast(
        child: MaterialApp(
          initialRoute: '/',
          onGenerateRoute: Router.generateRoute,
          builder: (context, child) {
            return NoScaleTextWidget(child: child);
          },
          title: '灵灵九',
          theme: dartTheme(),
          localizationsDelegates: [
            S.delegate,
            RefreshLocalizations.delegate,
            GlobalMaterialLocalizations.delegate,
            GlobalWidgetsLocalizations.delegate,
            GlobalCupertinoLocalizations.delegate
          ],
          supportedLocales: S.delegate.supportedLocales,
        ),
      ),
    );
  }
}

ThemeData dartTheme() {
  ThemeData base = ThemeData.dark();
  return base.copyWith(
    primaryColor: Color(0xffea537a),
    accentColor: Color(0xffea537a),
    scaffoldBackgroundColor: Colors.transparent,
    buttonTheme: base.buttonTheme.copyWith(
      textTheme: ButtonTextTheme.primary,
      height: 40,
      shape: StadiumBorder(),
      buttonColor: Color(0xffea537a),
    ),
    primaryTextTheme: base.primaryTextTheme.copyWith(
      title: base.primaryTextTheme.title.copyWith(
        fontSize: 18,
      ),
    ),
    inputDecorationTheme: base.inputDecorationTheme.copyWith(
      border: InputBorder.none,
    ),
    appBarTheme: base.appBarTheme.copyWith(
      color: Colors.transparent,
      elevation: 0,
    ),
  );
}

ThemeData lightTheme() {
  ThemeData base = ThemeData.light();
  return base.copyWith(
    primaryColor: Color(0xffea537a),
    accentColor: Color(0xffea537a),
    buttonTheme: base.buttonTheme.copyWith(
      textTheme: ButtonTextTheme.primary,
      height: 40,
      shape: StadiumBorder(),
      buttonColor: Color(0xffea537a),
    ),
  );
}
